import cookie from 'react-cookies';

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    // eslint-disable-next-line no-bitwise
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
  });
}

/**
 * 树形数据转换
 * 数组转树形数据结构
 * @param {Array<object>} data
 * @param {string} id
 * @param {string} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId', order = 'orderNum', changeProps = {}) {
  const res = [];
  const newData = [];
  let newPid = pid;
  let childrenKey = 'children';
  const temp = {};
  const changePropKeys = Object.keys(changeProps);

  data.sort((a, b) => a[order] - b[order]);

  for (let i = 0; i < data.length; i++) {
    if (changePropKeys.length > 0) {
      const item = {};
      item[id] = data[i][id];
      item[pid] = data[i][pid];
      for (const key in changeProps) {
        if (Object.hasOwnProperty.call(changeProps, key)) {
          const element = changeProps[key];
          item[key] = isNaN(data[i][element]) ? data[i][element] : String(data[i][element]);
          switch (element) {
            case pid:
              newPid = key;
              delete item[pid];
              break;
            case 'children':
              childrenKey = key;
              break;
            case id:
              delete item[id];
              break;
            default:
              break;
          }
        }
      }
      newData.push(item);
    } else {
      newData.push(data[i]);
    }
    temp[data[i][id]] = newData[i];
  }
  for (let k = 0; k < newData.length; k++) {
    if (temp[newData[k][newPid]] && newData[k][id] !== newData[k][newPid]) {
      if (!temp[newData[k][newPid]][childrenKey] || temp[newData[k][newPid]][childrenKey] === undefined) {
        temp[newData[k][newPid]][childrenKey] = [];
      }
      /*  if (!temp[data[k][newPid]]._level) {
        temp[data[k][newPid]]._level = 1;
      }
      data[k]._level = temp[data[k][newPid]]._level + 1; */
      temp[newData[k][newPid]][childrenKey].push(newData[k]);
    } else {
      res.push(newData[k]);
    }
    if (changePropKeys.length > 0) {
      delete newData[k][id];
      delete newData[k][pid];
    }
  }
  return res;
}
/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  cookie.remove('token');
}
